package com.cnebula.uas.authtoken.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.cnebula.uas.authtoken.service.TokenService;
import com.cnebula.uas.authtoken.util.Constant;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class AuthTokenServiceImpl implements TokenService {

	ObjectMapper mapper = new ObjectMapper();
	CloseableHttpClient client = HttpClients.createDefault();

	@Override
	public ResponseEntity<String> fetchToken(Map<String, String> payload, String tenant, String okapiURL,
			String requestToken) throws Exception {

		String url = okapiURL + "/token";
		Map<String, Map<String, String>> json = new HashMap<String, Map<String, String>>();
		json.put("payload", payload);

		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader(Constant.OKAPI_TOKEN_HEADER, requestToken);
		httpPost.addHeader(Constant.OKAPI_TENANT_HEADER, tenant);
		StringEntity se = new StringEntity(mapper.writeValueAsString(json), "utf-8");
		se.setContentEncoding("UTF-8");
		se.setContentType("application/json");
		httpPost.setEntity(se);

		CloseableHttpResponse res = null;
		String okapiToken;
		try {
			res = client.execute(httpPost);
			HttpEntity entity = res.getEntity();
			String content = EntityUtils.toString(entity);
			int statusCode = res.getStatusLine().getStatusCode();
			EntityUtils.consume(entity);
			if (statusCode != 200) {
				return ResponseEntity.status(statusCode).body(content);
			}
			Header token = res.getFirstHeader(Constant.OKAPI_TOKEN_HEADER);
			okapiToken = token.getValue();
		} finally {
			if (res != null) {
				res.close();
			}
		}

		return ResponseEntity.ok(okapiToken);
	}

	public static void main(String[] args) throws JsonProcessingException {
		Map<String, String> payload = new HashMap<String, String>();
		payload.put("sub", "zlj");
		payload.put("userId", "zlj_211010");

		Map<String, Map<String, String>> json = new HashMap<String, Map<String, String>>();
		json.put("payload", payload);

		ObjectMapper mapper = new ObjectMapper();
		String str = mapper.writeValueAsString(json);

		System.out.println(str);
	}

}
